<template>
  <!--创建账号-->
  <div class="register-form-div">
    <img v-if="role === 'AGENCY_OWNER'"
         src="@/assets/img/educatorgray.png"
         class="image"/>
    <h2 v-if="role === 'AGENCY_OWNER'">创建机构账号</h2>
    <el-form v-if="role === 'AGENCY_OWNER'"
             label-position="top"
             ref="registerFormRef"
             :model="accountInfo"
             :rules="rules"
             label-width="120px"
             class="demo-ruleForm"
    >
      <el-form-item prop="agencyName">
        <el-input :placeholder="$t('loc.agencyName')" v-model="accountInfo.agencyName" type="text" autocomplete="off"/>
      </el-form-item>

      <div class="flex-space-between">
        <el-form-item class="w-30-percent">
          <el-select v-model="accountInfo.prefix">
            <el-option
                v-for="item in prefixOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="lastName"  class="first-name-item w-full">
          <el-input :placeholder="$t('loc.lastName')" v-model="accountInfo.lastName" type="text" autocomplete="off"/>
        </el-form-item>
      </div>
      <el-form-item prop="firstName">
        <el-input :placeholder="$t('loc.1stName')" v-model="accountInfo.firstName" type="text" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="该邮箱将作为您的优先接收消息服务的邮箱" prop="primaryEmail">
        <el-input placeholder="primaryEmail" v-model="accountInfo.primaryEmail" type="text" autocomplete="off"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input show-password :placeholder="$t('loc.password')" v-model="accountInfo.password" type="password"
                  autocomplete="off"/>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
            :placeholder="$t('loc.cfmPwd')"
            v-model="accountInfo.confirmPassword"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button :loading="registering" style="width: 100%;height: 50px;font-size: 18px;" type="primary"
                   @click="submitForm('registerFormRef')">
          {{ $t('loc.confirmation') }}
        </el-button>
      </el-form-item>
      <div class="flex-row text-center m-t-sm">
        <div>
          <a class="text-primary" @click="goBack">上一步</a>
        </div>
        <div>
          <span style="margin-right: 8px">已有账号？</span>
          <router-link class="text-primary" :to="{name:'login'}">登录</router-link>
        </div>
      </div>
    </el-form>
    <img v-if="role === 'PARENT'"
         src="@/assets/img/parentgray.png"
         class="image"/>
    <h2 v-if="role === 'PARENT'">创建家长账号</h2>
    <el-form v-if="role === 'PARENT'"
             label-position="top"
             ref="registerFormRef"
             :model="accountInfo"
             :rules="rules"
             label-width="120px"
             class="demo-ruleForm"
    >


      <div class="flex-space-between">
        <el-form-item class="w-30-percent">
          <el-select v-model="accountInfo.prefix">
            <el-option
                v-for="item in prefixOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="lastName"  class="first-name-item w-full">
          <el-input :placeholder="$t('loc.lastName')" v-model="accountInfo.lastName" type="text" autocomplete="off"/>
        </el-form-item>
      </div>
      <el-form-item prop="firstName">
        <el-input :placeholder="$t('loc.1stName')" v-model="accountInfo.firstName" type="text" autocomplete="off"/>
      </el-form-item>
      <el-form-item prop="invitationCode">
        <el-input :placeholder="$t('loc.actCode')" v-model="accountInfo.invitationCode" type="text" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="该邮箱将作为您的优先接收消息服务的邮箱" prop="primaryEmail">
        <el-input placeholder="primaryEmail" v-model="accountInfo.primaryEmail" type="text" autocomplete="off"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input show-password :placeholder="$t('loc.password')" v-model="accountInfo.password" type="password"
                  autocomplete="off"/>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
            :placeholder="$t('loc.cfmPwd')"
            v-model="accountInfo.confirmPassword"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
<!--      选择家庭关系-->
      <el-form-item :label="$t('loc.relationShiptoChild')" prop="familyRelation">
        <el-input
            :placeholder="$t('loc.relationShiptoChild')"
            v-model="accountInfo.relationship"
            type="text"
        />
      </el-form-item>
      <el-form-item>
        <el-button :loading="registering" style="width: 100%;height: 50px;font-size: 18px;" type="primary"
                   @click="submitForm('registerFormRef')">
          {{ $t('loc.confirmation') }}
        </el-button>
      </el-form-item>
      <div class="flex-row text-center m-t-sm">
        <div>
          <a class="text-primary" @click="goBack">上一步</a>
        </div>
        <div>
          <span style="margin-right: 8px">已有账号？</span>
          <router-link class="text-primary" :to="{name:'login'}">登录</router-link>
        </div>
      </div>
    </el-form>



  </div>

</template>

<script>
import {UserRole} from "@/utils/constants";
import {validateEMail, validatePhoneTwo, validatePsdReg} from "@/utils/rules";
import {ElMessageBox} from "element-plus";
import {markRaw} from "vue";
import {Select} from '@element-plus/icons-vue'

export default {
  name: "registerForm",
  data: function () {
    let passwordValidator = (rule, value, callback) => {
      if (!validatePsdReg(value)) {
        callback(new Error(this.$t('loc.pwdShould8To20Char')));
      } else {
        if (this.accountInfo.confirmPassword !== '') {
          this.$refs['registerFormRef'].validateField('confirmPassword');
        }
        callback();
      }
    };
    let confirmPasswordValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.accountInfo.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      role: '',
      accountInfo: {      // 账号信息
        account: '',      // 注册账号 电话或邮箱
        primaryEmail: '', // 优先的服务邮箱
        agencyName: '',   // 机构名称
        prefix: '',          // 称谓前缀
        lastName: '',     // 姓
        firstName: '',     // 名
        password: '',     // 密码
        confirmPassword: '', // 确认密码
      },
      registering: false, // 是否正在注册
      prefixOptions: [
        {
          value: '',
          label: this.$t('loc.noPrefix'),
        },
        {
          value: 'Mr',
          label: this.$t('loc.Mr'),
        },
        {
          value: 'Miss',
          label: this.$t('loc.Miss'),
        },
      ],
      rules: {
        invitationCode: [
          {required: true, message: '请输入邀请码', trigger: 'blur'},
        ],
        agencyName: [
          {required: true, message: '请输入机构名', trigger: 'blur'},
        ],
        lastName: [
          {required: true, message: '请输入姓氏', trigger: 'blur'},
        ],
        firstName: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
        ],
        password: [
          {required: true, validator: passwordValidator, trigger: 'blur'},
        ],
        confirmPassword: [
          {required: true, validator: confirmPasswordValidator, trigger: 'change'},
        ],
      },
    }
  },
  watch: {
    // 時刻 监听路由
    '$route': {
      immediate: true,
      handler: function (to, from) {
        this.role = to.query.role;
        this.accountInfo.account = to.query.account;
        if (!this.role || !this.accountInfo.account || this.role === '' || !UserRole[this.role] || this.accountInfo.account === '') {
          this.$router.push({path: '/register'});
        }
        if (validateEMail(this.accountInfo.account)) {
          this.accountInfo.primaryEmail = this.accountInfo.account;
        }
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.role === UserRole['AGENCY_OWNER']) {
            this.registerOwner();
          } else if (this.role === UserRole['TEACHER']) {
            this.registerAgent();
          } else if (this.role === UserRole['PARENT']) {
            this.registerParent();
          } else {
            this.$message.error('注册失败');
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    registerSuccessHandler() {
      ElMessageBox.confirm(
          '恭喜你，注册成功！',
          this.$t('loc.confirmation'),
          {
            icon: markRaw(Select),
            showCancelButton: false,
            confirmButtonText: '去登录',
            customClass: 'message-box-custom',
          }
      ).then(() => {
        this.$router.replace({name: 'login'});
      }).catch(() => {
      });
    },
    registerOwner() {
      this.registering = true;
      let params = {
        account: this.accountInfo.account,
        primaryEmail: this.accountInfo.primaryEmail,
        agencyName: this.accountInfo.agencyName,
        prefix: this.accountInfo.prefix,
        lastName: this.accountInfo.lastName,
        firstName: this.accountInfo.firstName,
        password: this.accountInfo.password,
      };
      $axios.post($api.urls().registerOwner, params).then((res) => {
        this.registering = false;
        this.registerSuccessHandler();
      }).catch((error) => {
        this.registering = false;
        this.$message.error(error.response.data.description)
      });
      return false;
    },
    registerAgent() {

    },
    registerParent() {
      this.registering = true;
    let params = {
        account: this.accountInfo.account,
        primaryEmail: this.accountInfo.primaryEmail,
        prefix: this.accountInfo.prefix,
        lastName: this.accountInfo.lastName,
        firstName: this.accountInfo.firstName,
        password: this.accountInfo.password,
        invitationCode: this.accountInfo.invitationCode,
        relationship: this.accountInfo.relationship,
      };
      $axios.post($api.urls().registerParent, params).then((res) => {
        this.registering = false;
        this.registerSuccessHandler();
      }).catch((error) => {
        this.registering = false;
        this.$message.error(error.response.data.description)
      });
    },
    goBack() {
      this.$router.go(-1)
    }
  },
}
</script>

<style scoped lang="less">
.register-form-div {
  text-align: center;
  width: 500px;
  font-size: 18px;
  margin: 0 auto;
  padding: 20px 0;
}

.w-30-percent {
  width: 30%;
}

.w-70-percent {
  width: 70%;
}

.flex-row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.first-name-item {
  /deep/ .el-form-item__content {
    margin-left: 5px !important;
  }
}

.el-input {
  height: 50px;
}

/deep/ .el-input__wrapper {
  height: 50px;
  font-size: 18px;
}

/deep/ .el-form-item__content {
  margin: 0 !important;
}

</style>